package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrModuleVO;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IOrderService;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalAttrHelper;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.ServiceControlScopeCache;
import com.iwhalecloud.bss.kite.dataservice.entity.ServiceControlScope;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.scene.service.operate.OperateAttrService;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.handler.module.CommonAttrModuleHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <Description>集团用户模块-业务变更，部分属性可编辑 <br>
 * @author chenkaiwen<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2020-11-25<br>
 * @see com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module.GroupUserInfoAttrModuleHandler
 */
@Service
public class GroupUserInfoAttrModuleHandler extends CommonAttrModuleHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private OperateAttrService operateAttrService;
    @Autowired
    private IOrderService orderService;

    @Override
    public CommonAttrModuleVO dealExecuteSpecialAttr(AcceptContext context, SceneModule sceneModule, CommonAttrModuleVO defCommonAttrInfoVO) {
        String sceneInstId = context.getAcceptRequest().getSceneInstId();
        String moduleId = sceneModule.getKiteModule().getModuleId();
        List<KiteAttr> commonAttrs = querySceneInstService.listCommonAttrs(sceneInstId);

        String offerInstId = context.getAcceptRequest().getOfferInstId();
        String custId = context.getAcceptRequest().getCustId();
        KiteOfferInst kiteOfferInst = querySceneInstService.getOfferInst(custId, offerInstId);
        String specId = "1";
        String cateId = "";

        if(Objects.nonNull(kiteOfferInst)){
            Map<String, KiteAttr> attrMap = kiteOfferInst.getAttrMap();
            if (KiteMapUtils.isNotEmpty(attrMap)) {
                KiteAttr kiteAttr = attrMap.get("cateId");
                if (Objects.nonNull(kiteAttr)) {
                    specId = kiteAttr.getValue();
                    cateId = specId;
                }
            }
        }


        String serviceOfferId = context.getAcceptRequest().getServiceOfferId();
        StringBuffer paramBuffer = new StringBuffer(serviceOfferId);
        paramBuffer.append("-").append(specId);
        List<ServiceControlScope> serviceControlScopes = ServiceControlScopeCache.get(paramBuffer.toString());
        List<CommonAttrVO> commonAttrVoList = defCommonAttrInfoVO.getCommonAttrList();
        commonAttrVoList.removeIf(
            commonAttrVo -> !KiteStringUtils.equalsAny(commonAttrVo.getShowType(),KeyConsts.PROD_ATTR_SHOW_TYPE_D, KeyConsts.PROD_ATTR_SHOW_TYPE_M));
        /** 过户、用户信息变更不需要展示商品名称
         if (KiteStringUtils.equalsAny(serviceOfferId, "1073", "2549")) {
         commonAttrVoList.removeIf(
         commonAttrVo -> KiteStringUtils.isEqual("offer_name", commonAttrVo.getFieldName()));
         }*/

        // 五大双线 资源核查业务 追单环节,用户信息展示应和录入界面保持一致
        String bizType = querySceneInstService.getExtParameterValue(sceneInstId, "bizType");
        if (LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW.equals(serviceOfferId) && "1012".equals(bizType)
            && KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr())) {
            commonAttrVoList.removeIf(
                commonAttrVo -> !KiteStringUtils.equalsAny(commonAttrVo.getFieldName(), "offer_name",
                    LocalKeyConsts.BUSINESS_NUMBER, "group_user_name", "USR0001", "USR0002"));
        }

        // 趸交支付详情场景，用户信息只展示商品名称，业务号码，集团用户名称
        String payDetailFlag = querySceneInstService.getExtParameterValue(sceneInstId, "PAY_DETAIL_FLAG");
        if (KiteStringUtils.isNotEmpty(payDetailFlag) && KeyConsts.IFTRUE_T.equals(payDetailFlag)) {
            commonAttrVoList.removeIf(
                commonAttrVo -> !KiteStringUtils.equalsAny(commonAttrVo.getFieldName(), "offer_name", LocalKeyConsts.BUSINESS_NUMBER, "group_user_name"));
        }
        defCommonAttrInfoVO.setCommonAttrList(commonAttrVoList);
        commonAttrVoList.stream().forEach(commonAttrVO -> {
            for (ServiceControlScope serviceControlScope : serviceControlScopes) {
                if (KiteStringUtils.equals(commonAttrVO.getFieldName(), serviceControlScope.getFieldName())) {
                    commonAttrVO.setIsEdit(serviceControlScope.getIsEdit());
                    commonAttrs.stream().forEach(kiteAttr -> {
                        if (KiteStringUtils.equals(commonAttrVO.getFieldName(), kiteAttr.getFieldName())
                            && KiteStringUtils.equals(kiteAttr.getModuleId(), moduleId)) {
                            kiteAttr.setIsEdit(commonAttrVO.getIsEdit());
                        }
                    });
                    break;
                }
            }
        });
        // 云专线不展示以下信息
        if (KiteStringUtils.equals("2100971", cateId)) {
            commonAttrVoList.removeIf(
                commonAttrVo -> KiteStringUtils.isEqual("ORD10036", commonAttrVo.getFieldName()) ||
                    KiteStringUtils.isEqual("ORD10170", commonAttrVo.getFieldName()) ||
                    KiteStringUtils.isEqual("ORD10129", commonAttrVo.getFieldName()) ||
                    KiteStringUtils.isEqual("ORD10125", commonAttrVo.getFieldName()) ||
                    KiteStringUtils.isEqual("ORD10050", commonAttrVo.getFieldName()) ||
                    KiteStringUtils.isEqual("ORD10051", commonAttrVo.getFieldName()) ||
                    KiteStringUtils.isEqual("ORD10052", commonAttrVo.getFieldName()));
        }

        // 订单性质=（2：补录单），业务号码可编辑
        String orderNatureAttrValue = querySceneInstService.getCommonAttrValue(sceneInstId, LocalKeyConsts.ORDER_NATURE);
        for (CommonAttrVO commonAttrVO : commonAttrVoList) {
            if(KiteStringUtils.isEqual(commonAttrVO.getFieldName(), LocalKeyConsts.BUSINESS_NUMBER)) {
                commonAttrVO.setIsEdit(KiteStringUtils.isEqual(orderNatureAttrValue, "2") ? KeyConsts.IFTRUE_T: KeyConsts.IFTRUE_F);
                break;
            }
        }
        // 过户质检/重提环节重新组装老客户的用户信息
        String taskCode = querySceneInstService.getExtParameterValue(sceneInstId, "taskCode");
        if (KiteStringUtils.equalsAny(taskCode, "OrderResubmit", "OrderSignedCheckSHZWY", "OrderResubmitZWY")
            && KiteStringUtils
            .equals(ServiceOfferConsts.SERVICE_OFFER_TRANSFER, serviceOfferId)) {
            String orderId = this.querySceneInstService
                .getExtParameterValue(context.getSceneVo().getSceneInstId(), "outOrderId");
            Map<String, Object> orderInfo = orderService.getOrderDetail(orderId);
            KitePosDTO kitePosDTO = JSONObject
                .toJavaObject(JSON.parseObject(JSON.toJSONString(orderInfo)), KitePosDTO.class);
            List<KitePosAttrDTO> attrs = kitePosDTO.getCustomer().getAttrs();
            String oldUserLocationValue = "";
            String oldUserLocationValueDesc = "";
            String oldUserName = "";

            if (KiteListUtils.isNotEmpty(attrs)) {
                for (KitePosAttrDTO attr : attrs) {
                    if (KiteStringUtils.equals("oldUserLocation", attr.getCode())) {
                        oldUserLocationValue = attr.getValue();
                    }
                    if (KiteStringUtils.equals("oldUserName", attr.getCode())) {
                        oldUserName = attr.getValue();
                    }
                }
                List<String> valueList = new ArrayList<String>();
                valueList.add(oldUserLocationValue.split(",")[0]);
                valueList.add(oldUserLocationValue.split(",").length > 1 ? oldUserLocationValue.split(",")[1] : "");
                valueList.add(oldUserLocationValue.split(",").length > 2 ? oldUserLocationValue.split(",")[2] : "");
                oldUserLocationValueDesc = LocalAttrHelper.getRegionNames(valueList, SymbolConsts.HYPHEN);
            }
            for (KiteAttr commonAttr : commonAttrs) {
                if (KiteStringUtils.equals("user_location", commonAttr.getFieldName())) {
                    commonAttr.setValue(oldUserLocationValue);
                    commonAttr.setValueDesc(oldUserLocationValueDesc);
                }
                if (KiteStringUtils.equals("group_user_name", commonAttr.getFieldName())) {
                    commonAttr.setValue(oldUserName);
                    commonAttr.setValueDesc(oldUserName);
                }
            }
        }

        if (KiteStringUtils.equals(querySceneInstService.getExtParameterValue(sceneInstId, "isBatchAccept"), "T")) {
            defCommonAttrInfoVO.setIsShow("F");
        }

        // 批量受理部分环节，不允许编辑
        if (BatchAcceptUtil.isBatchNode(context.getAcceptRequest().getSceneInstId())) {
            defCommonAttrInfoVO.setIsEdit("F");
        }

        // 批量签订，不展示用户信息模块
        if (KiteStringUtils.equals("batchSIGN", querySceneInstService.getExtParameterValue(sceneInstId, "preTaskCode"))) {
            defCommonAttrInfoVO.setIsShow("F");
        }

        operateAttrService.setCommonAttrs(sceneInstId, commonAttrs);
        return defCommonAttrInfoVO;
    }

    @Override
    public CommonAttrModuleVO dealPreviewSpecialAttr(AcceptContext context, SceneModule sceneModule, CommonAttrModuleVO defCommonAttrInfoVO) {
        String sceneInstId = context.getAcceptRequest().getSceneInstId();
        List<CommonAttrVO> commonAttrVoList = defCommonAttrInfoVO.getCommonAttrList();
        String custId = context.getAcceptRequest().getCustId();
        String cateId = CuccPosServiceUtils.getCateId(sceneInstId, custId);
        // 云专线不展示以下信息
        if (KiteStringUtils.equals("2100971", cateId)) {
            commonAttrVoList.removeIf(
                commonAttrVo -> KiteStringUtils.isEqual("ORD10036", commonAttrVo.getFieldName()) ||
                    KiteStringUtils.isEqual("ORD10170", commonAttrVo.getFieldName()) ||
                    KiteStringUtils.isEqual("ORD10129", commonAttrVo.getFieldName()) ||
                    KiteStringUtils.isEqual("ORD10125", commonAttrVo.getFieldName()) ||
                    KiteStringUtils.isEqual("ORD10050", commonAttrVo.getFieldName()) ||
                    KiteStringUtils.isEqual("ORD10051", commonAttrVo.getFieldName()) ||
                    KiteStringUtils.isEqual("ORD10052", commonAttrVo.getFieldName()));
        }
        if (KiteStringUtils.equals(querySceneInstService.getExtParameterValue(sceneInstId, "preTaskCode"),
            "BatchSubOrderDetail")) {
            CommonAttrVO offerNameAttr = commonAttrVoList.stream()
                .filter(commonAttrVO -> KiteStringUtils.equals(commonAttrVO.getFieldName(), "offer_name")).findFirst().orElse(null);
            if (Objects.nonNull(offerNameAttr)) {
                String offerName = querySceneInstService.getSceneInst(sceneInstId).getSceneInstName();
                offerNameAttr.setValue(offerName);
                offerNameAttr.setValueDesc(offerName);
            }
        }
        return defCommonAttrInfoVO;
    }
}
